"""
事务处理控制
"""
from applications.extensions import db
from functools import wraps
from applications.common.utils.http import fail_api
import traceback

'''
rollback :是否回滚: True-回滚(默认),False-只提交不回滚
'''
def transactional(rollback : bool = True):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print('{} : 进入事务处理装饰器,是否回滚-{}'.format(str(func),'是' if rollback else '否'))
            result = fail_api(msg="事务回滚出错")
            try:
                result = func(*args, **kwargs)
                db.session.commit()
            except Exception as e:  
                err_info = traceback.format_exc()
                print(err_info)
                if rollback : db.session.rollback()
                raise e
                # return result
            else:  
                return result

        return wrapper

    return decorator